<template>
  <div class="personal_container">
    <!-- <h1>这是个人主页</h1> -->
    <div class="personal_box">
      <!-- 头像 -->
      <div class="image_box">
        <img :src="loadImg" alt="">
        <!-- <img src="@/assets/logo.png"> -->
        <br>
        <br>
        <span class="text">更换头像</span>
      </div>
        <!-- <el-upload
            class="upload-demo"
            ref="upload"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="onChangeMd"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="Upload">上传</el-button>      
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload> -->
        <el-row :gutter="2">
          <el-col :span="10" :offset="5">
            <input type="file" id="fileId" @change="onChangeMd">
          </el-col>
          <el-col :span="5">
            <el-button type="primary" plain size="small" round @click="Upload">上传</el-button>
          </el-col>
        </el-row>
        <br>

      <!-- 信息区 -->
      <el-row :gutter="0">
        <el-col :span="5" :offset="1"><span class="text">昵称：</span></el-col>
        <el-col :span="12">
          <el-input v-model="petname" disabled></el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip effect="dark" content="修改昵称" placement="top" :enterable="false" >
            <el-button type="info" plain icon="el-icon-edit" size="medium" circle @click="petDialogVisible=true"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <br>
      <el-row :gutter="0">
        <el-col :span="5" :offset="1"><span class="text">姓名：</span></el-col>
        <el-col :span="12">
          <el-input v-model="realname" disabled></el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip effect="dark" content="修改姓名" placement="top" :enterable="false" >
            <el-button type="info" plain icon="el-icon-edit" size="medium" circle @click="realDialogVisible=true"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <br>
      <el-row :gutter="0">
        <el-col :span="5" :offset="1"><span class="text">邮箱：</span></el-col>
        <el-col :span="12">
          <el-input v-model="email" disabled></el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip effect="dark" content="邮箱改绑" placement="top" :enterable="false" >
            <el-button type="info" plain icon="el-icon-edit" size="medium" circle @click="emailDialogVisible=true"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <br>
      <el-row :gutter="0">
        <el-col :span="5" :offset="1"><span class="text">密码：</span></el-col>
        <el-col :span="12">
          <el-input v-model="password" disabled></el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip effect="dark" content="修改密码" placement="top" :enterable="false" >
            <el-button type="info" plain icon="el-icon-edit" size="medium" circle @click="passDialogVisible=true"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>

      <!-- el-dialog 平时不可见 在点击修改昵称时跳出-->
      <el-dialog
      title="更改昵称"
      :visible.sync="petDialogVisible" 
      width="30%"
      :modal-append-to-body="false" 
      @close="petDialogClose"
      :before-close="petHandleClose"
      :close-on-click-modal="false">
        <span>
          <el-input  v-model="petnameDialog" placeholder="请输入新昵称"></el-input>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="petDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changePetname">确 定</el-button>
        </span>
      </el-dialog>

      <!-- el-dialog 平时不可见 在点击修改姓名时跳出-->
      <el-dialog
      title="更改姓名"
      :visible.sync="realDialogVisible" 
      width="30%"
      :modal-append-to-body="false" 
      @close="realDialogClose"
      :before-close="realHandleClose"
      :close-on-click-modal="false">
        <span>
          <el-input  v-model="realnameDialog" placeholder="请输入新姓名"></el-input>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="realDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeRealname">确 定</el-button>
        </span>
      </el-dialog>

      <!-- el-dialog 平时不可见 在点击修改邮箱时跳出-->
      <el-dialog
      title="改绑邮箱"
      :visible.sync="emailDialogVisible" 
      width="30%"
      :modal-append-to-body="false" 
      @close="emailDialogClose"
      :before-close="emailHandleClose"
      :close-on-click-modal="false">
        <el-row :gutter="20">
          <el-col :span="16"> 
            <el-input  v-model="emailDialog" placeholder="请输入新邮箱"></el-input>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="sendCode">发送验证码</el-button>
          </el-col>  
        </el-row>
        <br>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input  v-model="oldCode" placeholder="旧邮箱收到的验证码"></el-input>
          </el-col>  
          <el-col :span="12">
            <el-input  v-model="newCode" placeholder="新邮箱收到的验证码"></el-input>
          </el-col>  
        </el-row>

        <span slot="footer" class="dialog-footer">
          <el-button @click="emailDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeEmail">确 定</el-button>
        </span>
      </el-dialog>

      <!-- el-dialog 平时不可见 在点击修改密码时跳出-->
      <el-dialog
      title="修改密码"
      :visible.sync="passDialogVisible" 
      width="30%"
      :modal-append-to-body="false" 
      @close="passDialogClose"
      :before-close="passHandleClose"
      :close-on-click-modal="false">
        <span>
          <el-input  v-model="passwordDialog" placeholder="请输入新密码"></el-input>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="passDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changePassword">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  data(){
    return {
      //个人中心显示信息
      petname: '',
      realname: '',
      email: '',
      password: '/--------------------/',
      //修改输入框信息
      petnameDialog: '',
      realnameDialog: '',
      emailDialog: '',
      passwordDialog: '',
      //邮箱新旧验证码
      oldCode: '',
      newCode: '',
      //弹窗是否可见属性
      petDialogVisible: false,
      realDialogVisible: false,
      emailDialogVisible: false,
      passDialogVisible: false,
      //图片相关属性
      Img: '',
      name: '',
      loadImg: '',
      //头像对话框是否可见
      imgVisible: false,
      
    }
  },

  created() {
    this.getUserInfo();
    this.loadAvatar();
  },

  methods: {
    visibleChange(){
        this.imgVisible = !this.imgVisible;
    },

    //获取用户个人信息
    getUserInfo(){
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/info" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.petname = res.data.petname;
          this.realname = res.data.realname;
          this.email = res.data.email;
        }
      });
    },

    //加载头像
    loadAvatar(){
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/imageload" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.loadImg = res.data.base64;
        }
      });
    },

    //对话框操作函数
    changePetname(){
      if (this.petnameDialog === ''){
        this.$message.warning("请输入修改的昵称！");
        return;
      }
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/chpetname" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
          newpetname: this.petnameDialog,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
          this.getUserInfo();
        }
      });
      this.petDialogVisible = false;
    },
    changeRealname(){
      if (this.realnameDialog === ''){
        this.$message.warning("请输入修改的真实名称！");
        return;
      }
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/chrealname" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
          newrealname: this.realnameDialog,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
          this.getUserInfo();
        }
      });
      this.realDialogVisible = false;
    },
    changeEmail(){
      if (this.emailDialog === '' || this.oldCode === '' || this.newCode === ''){
        this.$message.warning("请输入修改的邮箱！");
        return;
      };
      if (this.oldCode === '' || this.newCode === ''){
        this.$message.warning("请输入邮箱收到的验证码！");
        return;
      };
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/chemail" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
          newemail: this.emailDialog,
          newemailcode: this.newCode,
          oldemailcode: this.oldCode,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
          this.getUserInfo();
        }
      });
      this.emailDialogVisible = false;
    },
    changePassword(){
      if (this.passwordDialog === ''){
        this.$message.warning("请输入修改的密码！");
        return;
      }
      const usertoken = this.$store.getters.getUser.user.usertoken;
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/change" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
          newpwd: this.passwordDialog,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
          this.getUserInfo();
        }
      });
      this.passDialogVisible = false;
    },

    //发送验证码
    sendCode(){
      if (this.emailDialog === ''){
        this.$message.warning("请输入修改的邮箱！");
        return;
      }
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/codechange" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          email: this.emailDialog,
          isbond: 'true',
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
        }
      });
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/users/codechange" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          email: this.email,
          isbond: 'false',
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.$message.success(res.data.message);
        }
      });
    },



    //图片更新
    onChangeMd(e){
        // var name = document.getElementById('fileId').files[0].name
        
        return new Promise(function (resolve, reject){
          let reader = new FileReader()
          let file = document.querySelector('input[type=file]').files[0];
          
        //   console.log(e.target.files[0])
          reader.onload = () => {

            let Img = reader.result

            resolve(Img)
            //this.Img = reader.result

          }
          if(file){
            reader.readAsDataURL(e.target.files[0]);
          }

        }).then(res => {
          //console.log("result: "+res)
          this.Img = res
        //   console.log(this.Img);
          //this.name = res.name
          this.name = document.getElementById('fileId').files[0].name
          //console.log("name: "+name)
        })
      },

    //加载图片
    Upload(){
        //console.log("name_then: "+this.name)
        //console.log(this.Img);
        //console.log(this.loadImg);
        this.$axios({
          method: 'post',
          url: '/users/imagesave',
          data: qs.stringify({
            usertoken: this.$store.getters.getUser.user.usertoken,
            base64: this.Img,
          })
        }).then(res => {
          if(!res.data.success){
            this.$message.error(res.data.message);
          }
          else{
            this.$message.success(res.data.message);
            this.loadAvatar();
          }
          console.log(res)
        //   this.init()
        })
            .catch(err => {
              console.log(err)
            })
      },

    //对话框关闭操作函数
    petDialogClose(){
      this.petnameDialog='',
      this.petDialogVisible=false
    },
    petHandleClose(){
      this.petDialogVisible=false
    },
    realDialogClose(){
      this.realnameDialog='',
      this.realDialogVisible=false
    },
    realHandleClose(){
      this.realDialogVisible=false
    },
    emailDialogClose(){
      this.emailDialog='',
      this.newCode = '',
      this.oldCode = '',
      this.emailDialogVisible=false
    },
    emailHandleClose(){
      this.emailDialogVisible=false
    },
    passDialogClose(){
      this.passwordDialog='',
      this.passDialogVisible=false
    },
    passHandleClose(){
      this.passDialogVisible=false
    },
  }
}
</script>

<style lang="less" scoped>
.personal_box {
  width: 450px;
  height: 420px;
  background-color: #fff;
  border-radius: 20px;
  margin: 0 auto;
  margin-top: 100px;

  .image_box{
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    margin: 0 auto;
    transform: translate(0%, -50%);
    background-color: #fff;
    img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
    }
  }
};
.text{
  font-size: 18px;
};
</style>